const fsExtra = require("fs-extra");
const fs = require("fs");
const { defineConfig, build } = require("vite");
const { resolve } = require("path");
const vue = require("@vitejs/plugin-vue");
const vueJsx = require("@vitejs/plugin-vue-jsx");

//入口文件夹
const entryDir = resolve(__dirname, "../packages");
//输出文件夹
const outDir = resolve(__dirname, "../lib");

//vite的基础配置
const baseConfig = defineConfig({
  configFile: false, //禁用vite.config.js配置文件
  publicDir: false, //静态资源文件夹
  plugins: [vue(), vueJsx()], //插件
});

//rollup配置
const rollupOptions = {
  external: ["vue", "vue-router"], //排除vue
  output: {
    globals: {
      vue: "Vue", //全局变量
    },
  },
};

//全量打包构建
const buildAll = async () => {
  await build({
    ...baseConfig, //基础配置
    build: {
      //构建配置
      rollupOptions, //rollup配置
      outDir,
      lib: {
        entry: resolve(entryDir, "index.ts"), //入口文件
        name: "bs-vue3-element-plus-components", // 库的全局变量名
        fileName: (format) => `index.${format}.js`, //输出文件名
        formats: ["es", "umd"], //输出格式
      },
    },
  });
};

/**
 * @description: 单组件打包构建
 * @param {*} name: 组件名称
 */
async function buildSingle(name) {
  await build({
    ...baseConfig, //基础配置
    build: {
      //构建配置
      rollupOptions, //rollup配置
      outDir: resolve(outDir, name), //输出文件夹
      lib: {
        entry: resolve(entryDir, name), //入口文件
        name: "index", //
        fileName: (format) => `index.${format}.js`, //输出文件名
        formats: ["es", "umd"], //输出格式
      },
    },
  });
}

//驼峰命名改为横杆命名
const transformComponentName = (name) => {
  return name.replace(/([A-Z])/g, "-$1").toLowerCase();
};

//每个组件生成package.json
const createPackageJson = async (name) => {
  const componentName = transformComponentName(name);
  const fileStr = `
  {
  "name": "${componentName}",
  "main": "index.umd.js",
  "module": "index.es.js",
  "style": "styles.css"
  }
  `;
  //输出文件
  fsExtra.outputFile(resolve(outDir, `${name}/package.json`), fileStr, "utf-8");
};

//打包成库
const buildLib = async () => {
  await buildAll();
  //获取组件名称组成的数组
  const components = fs.readdirSync(entryDir).filter((name) => {
    // 获取组件文件夹路径
    const componentDir = resolve(entryDir, name);
    // 判断是否为文件夹
    const isDir = fs.lstatSync(componentDir).isDirectory();
    // 判断文件夹内是否有index.ts 并且文件夹不是utils
    return (
      isDir &&
      fs.readdirSync(componentDir).includes("index.ts") &&
      name !== "utils"
    );
  });
  //遍历组件名称数组
  components.forEach(async (name) => {
    // console.log(name, "打包");
    await buildSingle(name);
    // console.log(name, "生成package-json");
    await createPackageJson(name);
  });
};
buildLib();
